package com.linktel.productionLine.service;
import java.util.Date;

import com.linktel.productionLine.EasyExcel.monthPlanning.model.WriteMonthlyPlanning;
import com.linktel.productionLine.common.ErrorCode;
import com.linktel.productionLine.dao.DailyPlanningDao;
import com.linktel.productionLine.dao.MonthlyPlanningDao;
import com.linktel.productionLine.entity.MonthlyPlanning;
import com.linktel.productionLine.entity.dto.monthlyPlanning.MonthlyPlanningKeyProcessDTO;
import com.linktel.productionLine.entity.dto.monthlyPlanning.MonthlyPlanningNumberDTO;
import com.linktel.productionLine.entity.query.monthlyPlanning.*;
import com.linktel.productionLine.exception.BusinessException;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 对 产线月度规划产能信息 的操作
 *
 * @Author HuangJiaHui
 * @Date 2023/8/25 10:26
 */
@Service
@AllArgsConstructor
public class MonthlyPanningService {

    private MonthlyPlanningDao monthlyPlanningDao;

    private BaseStepService baseStepService;

    private DailyPlanningDao dailyPlanningDao;


    /**
     * 根据用户id，查询对应产线月度规划产能信息（总览，不包括关键工序）
     *
     * @param commitUserId 用户id
     * @return 产线月度规划产能信息列表
     */
    public List<MonthlyPlanningNumberDTO> listMonthlyPlanningNumberDTO(Long commitUserId) {
        Set<MonthlyPlanningNumberDTO> monthlyPlanningNumberDTOSet = monthlyPlanningDao.listMonthlyPlanningNumberDTO(commitUserId);
        ArrayList<MonthlyPlanningNumberDTO> monthlyPlanningNumberList = new ArrayList<>(monthlyPlanningNumberDTOSet);
        return monthlyPlanningNumberList.stream().sorted(Comparator.comparing(MonthlyPlanningNumberDTO::getProductionLineCode)
                .thenComparing(MonthlyPlanningNumberDTO::getYear)
                .thenComparing(MonthlyPlanningNumberDTO::getMonth)).collect(Collectors.toList());
    }
    /**
     * 新增产线月度规划产能信息（总览，不包括关键工序）
     * 一个产线、同一个月只能有一条数据
     *
     * @param addMonthlyPlanningNumberQuery 新增的产线月度规划产能信息
     * @return 是否新增成功
     */
    public Boolean addMonthlyPlanningNumber(AddMonthlyPlanningNumberQuery addMonthlyPlanningNumberQuery) {
        String productionLineCode = addMonthlyPlanningNumberQuery.getProductionLineCode();
        Integer year = addMonthlyPlanningNumberQuery.getYear();
        Integer month = addMonthlyPlanningNumberQuery.getMonth();
        Integer planningNumber = addMonthlyPlanningNumberQuery.getPlanningNumber();
        Long currentUserId = addMonthlyPlanningNumberQuery.getCurrentUserId();
        if (productionLineCode == null || year == null || year <= 0 || month == null || month <= 0 || month > 12 || planningNumber == null || planningNumber <= 0 || currentUserId == null || currentUserId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "填写数据不合法，请重新填写");
        }
        List<MonthlyPlanning> monthlyPlanningIds = monthlyPlanningDao.getMonthlyPlanningCapacityInfo(productionLineCode, null, year.toString(), month.toString(), currentUserId);
        if (!CollectionUtils.isEmpty(monthlyPlanningIds)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "同一条产线、一个月只能有一条数据，不能重复添加");
        }
        return monthlyPlanningDao.addMonthlyPlanningNumber(productionLineCode, year, month, planningNumber, currentUserId);
    }

    /**
     * 修改产线月度规划产能信息（总览，不包括关键工序）
     * 1、一个产线、同一个月只能有一条数据。产线、年、月相当于主键，不能修改产线、年、月，则不存在这个问题
     * 2、修改该数据，所有跟这条数据一个产线、同一个月的相关数据都要修改
     *
     * @param editMonthlyPlanningNumberQuery 修改的产线月度规划产能信息
     * @return 是否修改成功
     */
    public Boolean editMonthlyPlanningNumber(EditMonthlyPlanningNumberQuery editMonthlyPlanningNumberQuery) {
        String productionLineCode = editMonthlyPlanningNumberQuery.getProductionLineCode();
        Long currentUserId = editMonthlyPlanningNumberQuery.getCurrentUserId();
        Integer year = editMonthlyPlanningNumberQuery.getYear();
        Integer month = editMonthlyPlanningNumberQuery.getMonth();
        Integer planningNumber = editMonthlyPlanningNumberQuery.getPlanningNumber();
        if (productionLineCode == null || year == null || year <= 0 || month == null || month <= 0 || planningNumber == null || planningNumber <= 0 || currentUserId == null || currentUserId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "填写数据不完整，请重新填写");
        }
        return monthlyPlanningDao.editMonthlyPlanningNumber(productionLineCode, year, month, currentUserId, planningNumber);

    }

    /**
     * 删除产线月度规划产能信息（总览，不包括关键工序）
     * 同时删除该月下所有日计划
     *
     * @param deleteMonthlyPlanningNumberQuery 删除的产线月度规划产能信息（总览，不包括关键工序）
     * @return 是否删除成功
     */
    @Transactional
    public Boolean deleteMonthlyPlanningNumber(DeleteMonthlyPlanningNumberQuery deleteMonthlyPlanningNumberQuery) {
        String productionLineCode = deleteMonthlyPlanningNumberQuery.getProductionLineCode();
        Integer year = deleteMonthlyPlanningNumberQuery.getYear();
        Integer month = deleteMonthlyPlanningNumberQuery.getMonth();
        Long currentUserId = deleteMonthlyPlanningNumberQuery.getCurrentUserId();
        if (productionLineCode == null || year == null || year <= 0 || month == null || month <= 0 || currentUserId == null || currentUserId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        dailyPlanningDao.deleteDailyPlanningByMonthlyPlanning(productionLineCode, year, month, null, currentUserId);
        return monthlyPlanningDao.deleteMonthlyPlanning(productionLineCode, year, month, currentUserId);
    }

    /**
     * 根据登录用户id、产线id，年、月查询所有关键工序信息
     *
     * @param listMonthlyPlanningKeyProcessQuery 请求封装
     * @return 产线月度规划产能信息列表
     */
    public List<MonthlyPlanningKeyProcessDTO> listMonthlyPlanningKeyProcessDTO(ListMonthlyPlanningKeyProcessQuery listMonthlyPlanningKeyProcessQuery) {
        String productionLineCode = listMonthlyPlanningKeyProcessQuery.getProductionLineCode();
        Integer year = listMonthlyPlanningKeyProcessQuery.getYear();
        Integer month = listMonthlyPlanningKeyProcessQuery.getMonth();
        Long commitUserId = listMonthlyPlanningKeyProcessQuery.getCommitUserId();
        if (productionLineCode == null || year == null || year <= 0 || month == null || month <= 0 || commitUserId == null || commitUserId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<MonthlyPlanningKeyProcessDTO> monthlyPlanningKeyProcessDTOS = monthlyPlanningDao.listMonthlyPlanningKeyProcessDTO(commitUserId, productionLineCode, year, month);
        return monthlyPlanningKeyProcessDTOS.stream().filter(item -> item.getKeyStepName() != null && !item.getKeyStepName().equals("")).collect(Collectors.toList());

    }

    /**
     * 新增产线月度规划关键工序信息
     * 一条产线，一个月，一个工序只能有一条数据，不能重复添加
     *
     * @param addMonthlyPlanningKeyProcessQuery 新增的产线月度规划关键工序信息封装
     * @return 是否新增成功
     */
    public Boolean addMonthlyPlanningKeyProcess(AddMonthlyPlanningKeyProcessQuery addMonthlyPlanningKeyProcessQuery) {
        Long currentUserId = addMonthlyPlanningKeyProcessQuery.getCurrentUserId();
        String productionLineCode = addMonthlyPlanningKeyProcessQuery.getProductionLineCode();
        Integer year = addMonthlyPlanningKeyProcessQuery.getYear();
        Integer month = addMonthlyPlanningKeyProcessQuery.getMonth();
        String keyStepCode = addMonthlyPlanningKeyProcessQuery.getKeyStepCode();
        Integer planningNumber = addMonthlyPlanningKeyProcessQuery.getPlanningNumber();
        Integer planningCapacity = addMonthlyPlanningKeyProcessQuery.getPlanningCapacity();
        Integer sort = addMonthlyPlanningKeyProcessQuery.getSort();
        if (productionLineCode == null || year == null ||planningNumber == null || planningNumber <= 0 || year <= 0 || month == null || month <= 0 ||
                currentUserId == null || currentUserId <= 0 || keyStepCode == null || planningCapacity == null || planningCapacity <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "填写数据不完整或者数据不合法，请重新填写");
        }
        String keyStepName = baseStepService.getBaseStepNameByCode(keyStepCode);
        if (StringUtils.isEmpty(keyStepName)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到该关键工序");
        }
        List<MonthlyPlanning> monthlyPlanningIds = monthlyPlanningDao.getMonthlyPlanningCapacityInfo(productionLineCode, keyStepCode, year.toString(), month.toString(), currentUserId);
        if (!CollectionUtils.isEmpty(monthlyPlanningIds)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "同一条产线、一个月、一个工序只能有一条数据，不能重复添加");
        }
        return monthlyPlanningDao.addMonthlyPlanningKeyProcess(productionLineCode, year, month, planningNumber, keyStepCode, keyStepName, planningCapacity, currentUserId, sort);

    }

    /**
     * 修改产线月度规划关键工序信息
     *
     * @param editMonthlyPlanningKeyProcessQuery 修改的产线月度规划关键工序信息封装
     * @return 是否修改成功
     */
    public Boolean editMonthlyPlanningKeyProcess(EditMonthlyPlanningKeyProcessQuery editMonthlyPlanningKeyProcessQuery) {
        Long currentUserId = editMonthlyPlanningKeyProcessQuery.getCurrentUserId();
        Long id = editMonthlyPlanningKeyProcessQuery.getId();
        Integer planningCapacity = editMonthlyPlanningKeyProcessQuery.getPlanningCapacity();
        Integer sort = editMonthlyPlanningKeyProcessQuery.getSort();
        if (id == null || id <= 0 || currentUserId == null || currentUserId <= 0 || planningCapacity == null || planningCapacity <= 0 || sort == null || sort <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "填写数据不完整，请重新填写");
        }
        return monthlyPlanningDao.editMonthlyPlanningKeyProcess(id, planningCapacity, sort, currentUserId);
    }
    /**
     * 删除产线月度规划关键工序信息
     *
     * @param deleteMonthlyPlanningKeyProcessQuery 删除的产线月度规划关键工序信息封装
     * @return 是否删除成功
     */
    @Transactional
    public Boolean deleteMonthlyPlanningKeyProcess(DeleteMonthlyPlanningKeyProcessQuery deleteMonthlyPlanningKeyProcessQuery) {
     Long id = deleteMonthlyPlanningKeyProcessQuery.getId();
     Long currentUserId = deleteMonthlyPlanningKeyProcessQuery.getCurrentUserId();
        if (id == null || id <= 0 || currentUserId == null || currentUserId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MonthlyPlanning monthlyPlanning = monthlyPlanningDao.getMonthlyPlanningById(id);
        String productionLineCode = monthlyPlanning.getProductionLineCode();
        String keyStepCode = monthlyPlanning.getKeyStepCode();
        Integer year = monthlyPlanning.getYear();
        Integer month = monthlyPlanning.getMonth();
        Long createdBy = monthlyPlanning.getCreatedBy();
        if (productionLineCode == null || year == null || year <= 0 || month == null || month <= 0 || createdBy == null || createdBy <= 0 || keyStepCode == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        dailyPlanningDao.deleteDailyPlanningByMonthlyPlanning(productionLineCode, year, month, keyStepCode, currentUserId);
        return monthlyPlanningDao.deleteMonthlyPlanningKeyProcess(id, currentUserId);
    }


    /**
     * 返回该用户的所有月度产能规划信息
     *
     * @param commitUserId 当前登录用户Id
     * @return 月度产能规划信息列表
     */
    public List<WriteMonthlyPlanning> downloadAttendanceDate(Long commitUserId) {
        return monthlyPlanningDao.listMonthlyPlanningDTO(commitUserId);
    }
}
